package com.bw.controller;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bw.annotation.LogAnno;
import com.bw.domain.BResult;
import com.bw.domain.User;
import com.bw.service.UserService;
import com.bw.util.JwtUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

@RestController
public class UserController {


    @Autowired
    UserService userService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RedisTemplate redisTemplate;

    @LogAnno
    @RequestMapping("/login")
    public BResult login(@RequestBody @Valid User login, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
        if (result.hasErrors()) {//  如果校验之后有异常

            return BResult.error(result.getAllErrors().get(0).getDefaultMessage());
        }

        User userDB = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getName, login.getName()));

        if (userDB == null) {
            return BResult.error("用户不存在");

        }
        String loginPassword = login.getPassword();
        String dbPassword = userDB.getPassword();
        String salt = userDB.getSalt();
        String md5Hex = DigestUtil.md5Hex(loginPassword + salt);

        if (!md5Hex.equals(dbPassword)) {
            Long increment = redisTemplate.opsForValue().increment(userDB.getName(), 1);
            //第一次输错密码 计时开始
            if (increment == 1) {
                redisTemplate.expire(userDB.getName(), 1, TimeUnit.MINUTES);
            }
            if (increment > 2) {
                redisTemplate.opsForValue().set("passwordLock:" + userDB.getName(),"1");
            }

            return BResult.error("密码错误");
        }
        // 登录成功后加密 用户 得到token，  并且设置过期时间为300分钟
        String token = JwtUtils.createToken(userDB, 300);
//        登录后创建token，并以token为key缓存用户信息
//        redissonClient.getBucket(token).set(1);
        redisTemplate.opsForValue().set(token, 1, 30, TimeUnit.MINUTES);

        Cookie cookie = new Cookie("token", token);
        response.addCookie(cookie);

        return BResult.success(token);

    }


    @RequestMapping("selectUserByToken")
    public User selectUserByToken(@RequestParam(value = "token",required = false) String token) throws InterruptedException {
//        int i =1/0;
        // 解密用户
        Thread.sleep(3*1000);
        User user = JwtUtils.getLoginUserFromRequest(token, User.class);
        System.out.println("解密用户-------" + user);
        return user;


    }
}
